package com.msb.servicedriveuser.service.impl;

import com.msb.commons.constant.CommonStatusEnum;
import com.msb.commons.constant.DriverCarConstant;
import com.msb.commons.response.ResponseResult;
import com.msb.commons.dto.DriverCarBindingRelationship;
import com.msb.servicedriveuser.mapper.DriverCarBindingRelationshipMapper;
import com.msb.servicedriveuser.service.DriverCarBindingRelationshipService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chshh
 * @since 2022-10-25
 */
@Service
public class DriverCarBindingRelationshipServiceImpl extends ServiceImpl<DriverCarBindingRelationshipMapper, DriverCarBindingRelationship> implements DriverCarBindingRelationshipService {
    @Resource
    private DriverCarBindingRelationshipMapper driverCarBindingRelationshipMapper;

    @Override
    public ResponseResult bind(DriverCarBindingRelationship driverCarBindingRelationship) {
        LocalDateTime now = LocalDateTime.now();

        driverCarBindingRelationship.setBindingTime(now);
        driverCarBindingRelationship.setBindState(DriverCarConstant.DRIVER_CAR_BIND);

        driverCarBindingRelationshipMapper.insert(driverCarBindingRelationship);
        return ResponseResult.success("");
    }

    @Override
    public ResponseResult unbind(DriverCarBindingRelationship driverCarBindingRelationship) {
        LocalDateTime now = LocalDateTime.now();

        HashMap<String , Object> hashMap = new HashMap<>();
        hashMap.put("driver_id",driverCarBindingRelationship.getDriverId());
        hashMap.put("car_id",driverCarBindingRelationship.getCarId());
        hashMap.put("bind_state",DriverCarConstant.DRIVER_CAR_BIND);

        List<DriverCarBindingRelationship> driverCarBindingRelationships = driverCarBindingRelationshipMapper.selectByMap(hashMap);

        if(driverCarBindingRelationships.isEmpty()){
            return ResponseResult.fail(CommonStatusEnum.DRIVER_CAR_BIND_NOT_EXISTS.getCode(),CommonStatusEnum.DRIVER_CAR_BIND_NOT_EXISTS.getValue());
        }

        DriverCarBindingRelationship driverCarBindingRelationship1 = driverCarBindingRelationships.get(0);
        driverCarBindingRelationship1.setBindState(DriverCarConstant.DRIVER_CAR_UNBIND);
        driverCarBindingRelationship1.setUnBindingTime(now);

        driverCarBindingRelationshipMapper.updateById(driverCarBindingRelationship1);

        return ResponseResult.success("");
    }
}
